package org.third.security.crypto;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import java.security.Key;
import java.security.spec.InvalidKeySpecException;

public class TestJce {
	public static void main(String[] args) {
		try {
			String initData = "332343adfasdf234";
			byte[] salt = initData.getBytes();
			PBEKeySpec pbeKeySpec;
			try {
				pbeKeySpec = new PBEKeySpec(initData.toCharArray(), initData.getBytes(), 12);
			} catch (Exception e) {
				throw new LWCryptoException("Unable to create PBEKeySpec object.", e);
			}

			String pbeCryptoAlgorithmName = "PBEWithMD5ANdTripleDES";
			SecretKeyFactory keyFact;
			try {
				keyFact = SecretKeyFactory.getInstance(pbeCryptoAlgorithmName);
			} catch (Exception e) {
				throw new LWCryptoException(
						"Unable to create an instance of SecretKeyFactory for cipher: " + pbeCryptoAlgorithmName, e);
			}

			Key key;
			try {
				key = keyFact.generateSecret(pbeKeySpec);
			} catch (InvalidKeySpecException e) {
				throw new LWCryptoException("Unable to create secret key from given spec", e);
			}

			Cipher cipher = Cipher.getInstance(pbeCryptoAlgorithmName);
			salt = new byte[8];
			System.arraycopy(initData.getBytes(), 0, salt, 0, salt.length);
			cipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, 20));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
